package logic

import (
	"cart_srv/model/mysql"
	"cart_srv/model/redis"
	"context"
	"errors"

	"cart_srv/cart"
	"cart_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *cart.CartAddRequest) (*cart.CartAddResponse, error) {
	//1.判断商品是否存在
	g := mysql.Good{}
	err := g.GoodsInfo(in.Goodsid)
	if err != nil {
		logx.Error("没有该商品")
		return nil, errors.New("没有该商品")
	}
	if g.ID == 0 {
		logx.Error("没有该商品")
		return nil, errors.New("没有该商品")
	}
	//2.判断库存是否充足
	stock := redis.GetStock(in.Goodsid)
	if stock < in.Num {
		logx.Error("库存不够")
		return nil, errors.New("库存不够")
	}
	//3.购物车有，累加。没有就添加。
	if redis.Exists(in.Userid, in.Goodsid) {
		err = redis.UpdateCart(in.Userid, in.Goodsid, in.Num)
		if err != nil {
			logx.Error("商品添加失败")
			return nil, errors.New("商品添加失败")
		}
	} else {
		Map := map[string]interface{}{
			"user_id":     in.Userid,
			"goods_id":    in.Goodsid,
			"goods_name":  g.GoodsName,
			"goods_price": g.GoodsPrice,
			"num":         in.Num,
			"checkout":    1,
		}
		err = redis.AddCart(Map)
		if err != nil {
			logx.Error("商品添加失败")
			return nil, errors.New("商品添加失败")
		}
	}
	return &cart.CartAddResponse{Success: true}, nil
}
